<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="部门名称" prop="partName" label-width="100px">
        <el-input v-model="queryParams.partName" placeholder="请输入部门名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="所属企业" prop="entID" label-width="100px">
        <el-select v-model="queryParams.entID" clearable placeholder="请选择所属企业" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options2" :key="item.id" :label="item.companyName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :data="roleList" row-key="id"  :indent="50"  :max-height="tableHeight" >
      <!-- <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="部门名称"  v-if="columns[0].visible" prop="partName" align="center" width="250" />
      <el-table-column label="部门编码"  v-if="columns[1].visible" prop="partCode" align="center" width="150" />
      <el-table-column label="部门备注"  v-if="columns[2].visible" prop="partDes" :show-overflow-tooltip="false" align="center" width="250" />
      <el-table-column label="所属企业"  v-if="columns[3].visible" prop="entName" align="center" width="250" />
      <el-table-column label="创建时间"  v-if="columns[4].visible" align="center"  width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="280px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="plus"  @click="handleUpdate2(scope.row)">添加下级部门</el-button>
          <el-button link type="primary" icon="Edit"  @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger"  icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="entID">
          <el-select v-model="form.entID" placeholder="请选择所属企业" @change="handleEntChange">
            <el-option v-for="item in options2" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上一级部门" prop="entID">
          <el-cascader style="width: 600px;" ref="cascaderRef" @change="handleCascaderChange" v-model="form.previousID"
            :options="options3"
            :props="{ checkStrictly: true,children:'children',label:'partName',value:'id',emitPath:false}" />
        </el-form-item>
        <el-form-item label="部门名称" prop="partName">
          <el-input v-model.trim="form.partName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门备注" prop="partDes">
          <el-input v-model="form.partDes" type="textarea" :maxlength="100" placeholder="请输入部门备注"  />
        </el-form-item>
      </el-form>
      <el-form-item label="部门状态" label-width="100">
        <el-radio-group v-model="form.state">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <MessagePopup ref="messagePopupRef" :show="hasNewMessage" @close="hasNewMessage = false" /> -->
  </div>
</template>

<script setup>
import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'

const userInfo = useInfoStore();
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");
const router = useRouter();
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const options2 = ref([]);
const data = reactive({
  form: {
    id: null,
    entID: null,
    previousID:  null,
    partName:  null,
    partDes: null,
    state: 1
  },
  queryParams: {
    pageNo : 1,
    pageSize: 10,
    entID:null,
    partName:null,
  },
  rules: {
    entID: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    partName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
  },
});
const cascaderRef = ref(null);
const options3 = ref([]);
const isUnshift = ref(true);

// 列显隐信息
const columns = ref([
  { key: 0, label: `部门名称`, visible: true },
  { key: 1, label: `部门编码`, visible: true },
  { key: 2, label: `部门备注`, visible: true },
  { key: 3, label: `所属企业`, visible: true },
  { key: 4, label: `创建时间`, visible: true },
]);

const { queryParams, form, rules } = toRefs(data);

/** 查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetListCom({}).then(response => {
    if (response.data) {
      options2.value = response.data || [];
    }
  });
}
// 企业下拉选择
function handleEntChange(value) {
  _GetListDepart();
}
/** 查询部门列表下拉 */
function _GetListDepart(flag=false) {
  proxy.cloudTv_API.GetListDepart({entID:form.value.entID}).then(response => {
    options3.value = response.data;
    if(isUnshift.value){ //开关状态
      options3.value.unshift({partName:'直属部门',id:0});
    }
    form.value.previousID = form.value.previousID?form.value.previousID:options3.value[0].id;
  });
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetPageListDepart(queryParams.value).then(response => {
    roleList.value = response.data.list;
    total.value = response.data.total || 0;
    loading.value = false;
  });
}
  // 主动关闭弹层
function handleCascaderChange(e) {
    // 获取当前选中的节点列表
    const item = cascaderRef.value.getCheckedNodes()[0].data;
    form.value.previousID = item?.id;
    cascaderRef.value.togglePopperVisible(false)
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除部门名称"' + row.partName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelDepart({ id: row.id }).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: null,
    entID: null,
    previousID: null,
    partName: null,
    partDes: null,
    state: 1
  };
  // 添加默认第一个
  form.value.entID = form.value.entID?form.value.entID:options2.value[0].id;
  proxy.resetForm("roleRef");
}

/** 添加 */
function handleAdd() {
  isUnshift.value = true;
  reset();
  _GetListDepart();
  open.value = true;
  title.value = "新增";
}
/** 添加下级 */
function handleUpdate2(row) {
  isUnshift.value = false;
  reset();
  form.value.entID = row.entID;
  form.value.previousID = row.id;
  _GetListDepart();
  open.value = true;
  title.value = "添加下级支线";
}
/** 修改 */
function handleUpdate(row) {
  isUnshift.value = true;
  reset();
  // 填充表单数据
  Object.keys(form.value).forEach(key => {
    form.value[key] = row[key];
    if (form.value[key] == undefined) {
      form.value[key] = null
    }
  });
  _GetListDepart();
  open.value = true;
  title.value = "修改";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.UpdateDepart({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddDepart(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getGetEnterpriseList();
getList();
</script>

<style lang="scss" scoped>

:deep(.el-table__expand-icon .el-icon){
    font-size: 14px !important; 
}
</style>